<template>
  <el-upload
    class="avatar-uploader"
    action=""
    list-type="picture-card"
    :http-request="uploadPicture_new"
    :headers="headers"
    :on-preview="handlePictureCardPreview"
    :on-exceed="handleDetailExce_new"
    :on-change="handleLimit_new"
    :on-remove="handleDetailRemove_new"
    :file-list="imgList"
    :limit="limit"
    :multiple="false"
    :class="{disabled:uploadDisabled_new}"
    :before-upload="beforeUpload"
  />
</template>

<script>
import { uploadPicture } from '@/api/common'
import { getToken } from '@/utils/auth'

export default {
  name: 'SingleImageUpload',
  props: ['imgList'],
  data() {
    return {
      limit: 1,
      pictureUrl: '',
      deletePictureList: [],
      uploadDisabled_new: false,
      dialogImageUrl: '',
      dialogVisible_picture: false
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  methods: {
    // LOGO
    uploadPicture_new(params) {
      var formData = new FormData()
      formData.append('file', params.file)
      uploadPicture(formData).then((res) => {
        this.pictureUrl = res.url
        // 使用 $emit派发事件
        this.$emit('uploaded', this.pictureUrl)
      })
    },
    beforeUpload(file) {
      let isCanUpload = true
      if (file.size / 1024 / 1024 > 2) {
        isCanUpload = false
        this.$notify({
          title: '上传失败',
          message: '图片大小超过2M',
          type: 'warning',
          duration: 2000
        })
      }
      return isCanUpload
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible_picture = true
    },
    handleDetailExce_new() {
      this.$message({
        type: 'error',
        message: `上传文件个数超出限制!最多上传${this.limit}张图片!`
      })
    },
    handleLimit_new(file, fileList) {
      this.uploadDisabled_new = fileList.length >= this.limit
    },
    handleDetailRemove_new(file, fileList) {
      // this.temp.iconUrl = fileList
      this.uploadDisabled_new = fileList.length >= this.limit
      if (file.id) {
        this.deletePictureList.push(file.id)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.disabled .el-upload--picture-card {
  display: none;
}
</style>
